<template>
  <div class="app-container">
    <el-form ref="dreamForm" :model="dreamForm" label-width="120px">
      <el-form-item :label="translation.title"
                    prop="title"
                    :rules="[{ required: true, message: 'Title can not be emplty' }]">
        <el-input v-model="dreamForm.title" />
      </el-form-item>

      <el-form-item :label="translation.classification">
        <el-select v-model="dreamForm.degree_info.degree_code" placeholder="Select a classification" clearable>
          <el-option v-for="(degree, index) in classification.degree" :key="index"
                     :label="degree.degree_code" :value="degree.degree_code">
            {{ degree.degree_code }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="translation.occured_time">
        <el-col :span="11">
          <el-date-picker v-model="dreamForm.dream_date" type="date" placeholder="Pick a date" style="width: 100%;" />
        </el-col>

      </el-form-item>
      <el-form-item :label="translation.psbtags">
        <el-button type="primary" size="small"
                   @click="onAddTag(ele)" v-for="ele in possibleTags"
                  :key="ele.key">
          {{ele.value}}
      </el-button>
      </el-form-item>
      <el-form-item :label="translation.tags">
        <tags-input element-id="tags" :add-tags-on-space="true"
                    :add-tags-on-comma="true" :allow-duplicates="false"
                    :existing-tags="dreamForm.tags"
          v-model="dreamForm.tags"></tags-input>
      </el-form-item>

      <el-form-item label="Privacy">
        <el-switch v-model="dreamForm.is_private" />
      </el-form-item>

      <el-form-item :label="translation.story"
                    prop="content"
                    :rules="[{ required: true, message: 'Main story can not be empty!'}]">
          <tinymce v-model="dreamForm.content" :height="300" />
           <!-- <markdown-editor ref="markdownEditor" v-model="dreamForm.content" -->
           <!-- :options="{hideModeSwitch:true,previewStyle:'tab'}" height="200px"> -->
          <!-- </markdown-editor> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button @click="onCancel">Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDreamById, updateDreamById } from '@/api/dreams'
import { getClassification } from '@/api/classification'
import tagsInput from './components/tagsInput'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'EditDream',
  components: { tagsInput, Tinymce  },
  data() {
    return {
      isEdit: true,
      listLoading: true,
      dreamForm: {
        title: "Title"
      },
      classification: { title: "", degree: [] },
      translation: {
        title: 'Dream Title',
        classification: 'Level',
        occured_time: 'Occured at',
        psbtags:'Possible tags',
        tags: 'Tags',
        story: 'Main Story'
      },
      keyTag: 1,
      possibleTags: [],
      currentDegree: ""
    }
  },
  watch: {
    dreamForm: {
      handler(newVal, oldVal){
        if (this.currentDegree != newVal['degree_info']['degree_code']){
          this.currentDegree = newVal['degree_info']['degree_code']
          this.loadPossibleTags()
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      // this.fetchClassification()
      // this.fetchDream(id)
      this.fetchData(id)
    } else {

    }
  },
  methods: {
    fetchData(id) {
      // this.listLoading = true
      getDreamById(id).then(response => {
        console.log('get data: ')
        console.log(response)
        if (response.data) {
          this.dreamForm = response.data
          this.currentDegree = this.dreamForm.degree_info.degree_code
          this.fetchClassification()
        }
        // this.listLoading = false
      })
    },
    fetchClassification() {
      // this.listLoading = true
      getClassification().then(response => {
        console.log(response)
        if (response.code === 20000){
          if (this.classification.title == 'default') {
            this.classification.degree = []
          } else {
            this.classification.title = response.data.title
            this.classification.degree = response.data.degree
            this.classification._id = response.data._id
            console.log('load classification done: ')
            console.log(this.classification)
            this.loadPossibleTags()
          }
        }
      })
    },
    loadPossibleTags() {
      for (var i = 0; i < this.classification.degree.length; ++i) {
        if (this.currentDegree === this.classification.degree[i].degree_code) {
          this.possibleTags = this.classification.degree[i].possible_tags
          break
        }
      }
    },
    onSubmit() {
      console.log(this.dreamForm)
      this.$refs.dreamForm.validate(valid => {
        if (valid) {
          updateDreamById(this.dreamForm).then(response => {
            console.log(response)
            if (response.code === 20000) {
              console.log('Update DREAM OK')
              this.$router.push('/nightmares/read_dream/' + this.dreamForm._id)
            }
          })
        }
      })
    },
    onCancel() {
      this.$router.go(-1)
    },
    onAddTag(tag) {
      if (this.dreamForm.tags.length === 0) {
        this.dreamForm.tags.push(tag)
        this.keyTag = this.keyTag + 1
      }
      var tagExist = false
      for (var i = 0; i < this.dreamForm.tags.length; ++i) {
        if (tag.value == this.dreamForm.tags[i].value) {
          tagExist = true
          break
        }
      }
      if (!tagExist) {
        this.dreamForm.tags.push( tag )
        this.keyTag = this.keyTag + 1
      }
    }
  }
}
</script>

<style scoped>
.editor-container {
  margin-bottom: 30px;
}
</style>
